<template>
  <screenContainer>
    <div class="board-box ant-board">
      <div class="__left">
        <div class="__left-top">
          <div class="__header-1">一次能源</div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">电用量</div>
            </div>
            <div class="chart-chart" id="chart1"></div>
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">自来水用量</div>
            </div>
            <div class="chart-chart" id="chart2"></div>
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">N2用量</div>
            </div>
            <div class="chart-chart" id="chart3"></div>
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">天然气用量</div>
            </div>
            <div class="chart-chart" id="chart4"></div>
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">化学品用量</div>
            </div>
            <div class="chart-chart" id="chart5"></div>
          </div>
        </div>
        <div class="__left-bottom">
          <div class="__header-1">电能单耗用量</div>
          <div class="bottom-chart" id="chart6"></div>
        </div>
      </div>
      <div class="__middle">
        <div class="__middle-top">
          <div class="__header-3">各分厂能耗占比</div>
          <div class="__middle-top-box">
            <div class="__middle-top-item" v-for="(item, index) in data.middleTop" :key="item.name"  ref="lines" :style="{
                 width: getPercent(item.percent)
              }">
              
              <div class="__item-line"></div>
              <div class="__item-bar"></div>
            </div>
            <div class="__item-text">
              <div class="__item-text-item" v-for="(item, index) in data.middleTop" :key="item.name" >
                {{ item.name }}：{{ getPercent(item.percent) }}
              </div>
            </div>
          </div>
        </div>
        <div class="__middle-bottom">
          <div class="__header-2">消耗使用</div>
          <div class="__middle-bottom-box">
            <div class="__middle-bottom-item">
              <div class="__header-1">ARRAY</div>
              <div class="__item-chart-box">
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">ARRAY能源成本占比</div>
                  </div>
                  <div class="chart-chart" id="chart_m_1"></div>
                </div>
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">ARRAY投产量&产量</div>
                  </div>
                  <div class="chart-chart" id="chart_m_2"></div>
                </div>
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">ARRAY单耗</div>
                  </div>
                  <div class="chart-chart" id="chart_m_3"></div>
                </div>
              </div>
            </div>
            <div class="__middle-bottom-item">
              <div class="__header-1">CF</div>
              <div class="__item-chart-box">
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">CF能源成本占比</div>
                  </div>
                  <div class="chart-chart" id="chart_m_4"></div>
                </div>
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">CF投产量&产量</div>
                  </div>
                  <div class="chart-chart" id="chart_m_5"></div>
                </div>
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">CF单耗</div>
                  </div>
                  <div class="chart-chart" id="chart_m_6"></div>
                </div>
              </div>
            </div>
            <div class="__middle-bottom-item">
              <div class="__header-1">CELL</div>
              <div class="__item-chart-box">
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">CELL能源成本占比</div>
                  </div>
                  <div class="chart-chart" id="chart_m_7"></div>
                </div>
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">CELL投产量&产量</div>
                  </div>
                  <div class="chart-chart" id="chart_m_8"></div>
                </div>
                <div class="chart-box">
                  <div class="chart-title">
                    <div class="block-header">CELL单耗</div>
                  </div>
                  <div class="chart-chart" id="chart_m_9"></div>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
      <div class="__right">
        <div class="top">
          <div class="__header-1">室外工况</div>
          <a-tabs v-model:activeKey="currentTab" class="top-content" size="small">
            <a-tab-pane v-for="item in rightTopTab" :key="item.itemName" :tab="item.itemName" />
          </a-tabs>
          <div class="data-box">
            <Outerdoor v-if="currentTab === '工况'" :data="outerdoorData" />
            <OriginalLine v-else class="chart" :loading="loadingRightTopRef" :chartData="rightTopData" theme="dark"
              :bordered="false" />
          </div>
        </div>
        <div class="__right-top">
          <div class="__header-1">加工/转换</div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">COP</div>
            </div>
            <div class="chart-chart" id="chart_r_1"></div>
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">压缩空气单价</div>
            </div>
            <div class="chart-chart" id="chart_r_2"></div>
          </div>
          <div class="chart-box">
            <div class="chart-title">
              <div class="block-header">纯废水单价</div>
            </div>
            <div class="chart-chart" id="chart_r_3"></div>
          </div>
        </div>
        <div class="__right-bottom">
          <div class="__header-1">动力费用</div>
          <div class="bottom-chart" id="chart_r_4"></div>
        </div>
      </div>

    </div>
    <div class="premiss-mask" v-if="!hasPremission">
      <img class="locked" src="../compNew/images/wuquanxian.svg" alt="">
      <p>暂无访问权限</p>
    </div>
  </screenContainer>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch, onUnmounted, nextTick, onBeforeUnmount, toRaw, computed } from 'vue';
import screenContainer from '../compNew/boadrContainer.vue';
import { getDictListByCode } from '@/api/sys/dict';
import { getChartChildListData, getTemperatureAndHumidityTwoDay } from '@/api/common/chart';
import Outerdoor from './outdoor.vue';
import dayjs from 'dayjs';
import useBar from './useBar';
import useBar2 from './useBar2';
import useLine from './useLine';
import usePie from './usePie';
import useData from './useData';
import OriginalLine from '@/components/Charts/Line/OriginalLine.vue';
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user.ts'

const router = useRouter()
const lines = ref()
const currentTab = ref('工况');
const rightTopTab = ref<any[]>([]);
const rightTopData = ref();
const outerdoorData = ref<any[]>([]);
const loadingRightTopRef = ref(false);
const rightTopDictCode = 'outdoor_temperature_and_humidity';

// 容器高度监听相关变量
const containerHeight = ref(0);
const resizeObserver = ref<ResizeObserver | null>(null);
const isRefreshing = ref(false); // 防止重复刷新
const userStore = useUserStore()
const roleList:any = toRaw(userStore.getRoleList) || []
console.log(roleList, 'roleList')
const hasPremission = computed(() => {
  return roleList.includes('12')
})
const imgs = {
  '3': new URL('../compNew/images/b20/headerbg3.png', import.meta.url).href,
  '2': new URL('../compNew/images/b20/headerbg2.png', import.meta.url).href,
  '1': new URL('../compNew/images/b20/headerbg1.png', import.meta.url).href,
};

// 定时器引用
let timeoutId: null | number = null;
let intervalId: null | number = null;

// 计算距离下一个整点或半点的时间间隔（毫秒）
const getTimeUntilNextHalfOrFullHour = () => {
  const now = dayjs();
  const minutes = now.minute();

  let nextTime;

  if (minutes < 30) {
    nextTime = now.minute(30).second(0).millisecond(0);
  } else {
    nextTime = now.add(1, 'hour').minute(0).second(0).millisecond(0);
  }

  return nextTime.diff(now);
};

// 清除所有定时器
const clearAllTimers = () => {
  if (timeoutId !== null) {
    window.clearTimeout(timeoutId);
    timeoutId = null;
  }
  if (intervalId !== null) {
    window.clearInterval(intervalId);
    intervalId = null;
  }
};

// 设置定时器
const setupTimers = () => {
  clearAllTimers();

  const timeToNext = getTimeUntilNextHalfOrFullHour();

  timeoutId = window.setTimeout(() => {
    getRightTopData();

    intervalId = window.setInterval(() => {
      getRightTopData();
    }, 30 * 60 * 1000);
  }, timeToNext);
};

// 提前定义需要在watch中使用的函数
const getOutdoorData = () => {
  getTemperatureAndHumidityTwoDay({
    dictCode: rightTopDictCode,
    itemName: '1号楼'
  }).then((res) => {
    outerdoorData.value = res;
  });
};

const createImageUrl = () => {
  document.documentElement.style.setProperty('--screenheaderbg1', `url(${imgs['1']})`);
  document.documentElement.style.setProperty('--screenheaderbg2', `url(${imgs['2']})`);
  document.documentElement.style.setProperty('--screenheaderbg3', `url(${imgs['3']})`);
};
createImageUrl();
const { data } = useData();


// 现在可以安全地使用getOutdoorData
watch(
  () => currentTab.value,
  (newValue) => {
    newValue === '工况' ? getOutdoorData() : getRightTopData();
  },
  { immediate: true }
);

const getRightTopTab = () => {
  getDictListByCode(rightTopDictCode).then(res => {
    rightTopTab.value = res;
    const temp = { ...res[0], itemName: '工况', itemId: '1', itemCode: '1' };
    rightTopTab.value.unshift(temp);
    currentTab.value = temp.itemName;
  });
};

const getRightTopData = () => {
  loadingRightTopRef.value = true;
  getChartChildListData({
    queryType: 'day',
    startDay: dayjs().format('YYYY-MM-DD'),
    dictCode: rightTopDictCode,
    itemName: currentTab.value
  }).then((res) => {
    rightTopData.value = res;
  }).catch(error => {
    console.error('获取数据失败:', error);
  }).finally(() => {
    loadingRightTopRef.value = false;
  });
};

// 容器高度监听函数
const handleContainerResize = (entries: ResizeObserverEntry[]) => {
  for (const entry of entries) {
    const newHeight = entry.contentRect.height;
    containerHeight.value = newHeight;

    // 检查高度是否超过5000px
    if (newHeight > 5000 && !isRefreshing.value) {
      isRefreshing.value = true;
      console.log('容器高度超过5000px，即将刷新页面');
      // 延迟刷新以确保用户看到提示
      setTimeout(() => {
        window.location.reload();
      }, 500);
    }
  }
};
// 处理各分厂能耗占比 不同比例下，提示的显示位置
watch(() => data.middleTop, (val) => {
  nextTick(() => {
    let totalLength = document.querySelector('.__middle-top-box').offsetWidth-24
    let lens:any[] = []
    let textLens:ay[] = []
    lines.value.forEach((item, index) => {
      console.log(item.offsetWidth)
      const width = item.offsetWidth
      lens.push(width)
      
      const textDoms = document.querySelectorAll('.__item-text-item')
      const textDom = textDoms[index]
      console.log(textDom, 'textDom')
      const textWidth = textDom.offsetWidth
      console.log(textWidth)
      if(index === 0) {
        if (width + 20 < textWidth) {
          textDom.style = `transform: translateX(${12}px)`
          textLens.push(textWidth+12)
        } else {
          textDom.style = `transform: translateX(${-textWidth/2+width/2}px)`
          textLens.push(-textWidth/2+width/2+textWidth)
        }
      }
      if (index === 1) {
        if (width + 20 < textWidth) {
          if (width + lens[index-1] + 20 < textWidth) {
            textDom.style = `transform: translateX(${textLens[index-1] + 12}px)`
            textLens.push(textLens[index-1] + 12+textWidth)
          } else if (totalLength - (width + lens[index - 1] +20) < textWidth ) {
            textDom.style = `transform: translateX(${totalLength - textWidth - 24 - textDoms[2].offsetWidth}px)`
            textLens.push(totalLength - textWidth - 24 - textDoms[2].offsetWidth)
          } else {
            textDom.style = `transform: translateX(${lens[index-1] + 12}px)`
            textLens.push(lens[index-1] + 12+textWidth)
          }
        } else {
          textDom.style = `transform: translateX(${-textWidth/2+width/2 + lens[index-1]}px)`
          textLens.push(-textWidth/2+width/2 + lens[index-1]+textWidth)
        }
      }
      if (index === 2) {
        if (width + 20 < textWidth) {
          textDom.style = `transform: translateX(${totalLength - textWidth - 12}px)`
        } else {
          textDom.style = `transform: translateX(${-textWidth/2+width/2 + lens[index-1]+lens[index - 2]}px)`
        }
      }
    })
  })
})
onMounted(() => {
  getRightTopTab();
  setupTimers();


  // DOM加载完成后初始化ResizeObserver
  nextTick(() => {
    const container = document.querySelector('.board-box');
    if (container) {
      resizeObserver.value = new ResizeObserver(handleContainerResize);
      resizeObserver.value.observe(container);

      // 初始检查一次容器高度
      handleContainerResize([{ contentRect: container.getBoundingClientRect() }] as ResizeObserverEntry[]);
    }
  });
});

const getPercent = (percent) => {
  if (!percent) return `33%`;
  const num = percent * 100;
  return `${num.toFixed(2)}%`;
};

// 图表初始化代码
useLine({
  id: 'chart1',
  data: data,
  key: 'left1',
  yname: '单位：kwh',
  handleClick: (params) => {
    router.push('/power/electricity/kwhpicture')
  }
});

useLine({
  id: 'chart2',
  data: data,
  key: 'left2',
  yname: '单位：m³',
  handleClick: (params) => {
    router.push('/power/water/redirect')
  }
});

useLine({
  id: 'chart3',
  data: data,
  key: 'left3',
  yname: '单位：Nm³',
  handleClick: () => {
    router.push('/power/gas/redirect')
  }
});

useLine({
  id: 'chart4',
  data: data,
  key: 'left4',
  yname: '单位：m³',
  handleClick: () => {
    router.push('power/airConditioning/redirect')
  }
});

useLine({
  id: 'chart5',
  data: data,
  key: 'left5',
  yname: '单位：m³',
  handleClick: () => {
    router.push('power/airConditioning/redirect')
  }
});

useLine({
  id: 'chart6',
  data: data,
  key: 'left6',
  colorKey: '2',
  yname: '单位：元/m²',
});

usePie({
  id: 'chart_m_1',
  data: data,
  key: 'middle1',
});

usePie({
  id: 'chart_m_4',
  data: data,
  key: 'middle4',
});

usePie({
  id: 'chart_m_7',
  data: data,
  key: 'middle7',
});

useLine({
  id: 'chart_m_2',
  data: data,
  key: 'middle2',
  colorKey: '1',
  hideRightTick: true,
  ynames: ['单位：元', '单位：元/m²'],
  names: ['单耗', '费用']
});

useLine({
  id: 'chart_m_3',
  data: data,
  key: 'middle3',
  colorKey: '1',
  hideRightTick: true,
  ynames: ['单位：元', '单位：元/m²'],
  names: ['单耗', '费用']
});

useLine({
  id: 'chart_m_5',
  data: data,
  key: 'middle5',
  colorKey: '1',
  hideRightTick: true,
  ynames: ['单位：元', '单位：元/m²'],
  names: ['单耗', '费用']
});

useLine({
  id: 'chart_m_6',
  data: data,
  key: 'middle6',
  colorKey: '1',
  hideRightTick: true,
  ynames: ['单位：元', '单位：元/m²'],
  names: ['单耗', '费用']
});

useLine({
  id: 'chart_m_8',
  data: data,
  key: 'middle8',
});

useLine({
  id: 'chart_m_9',
  data: data,
  key: 'middle9',
  colorKey: '1',
  hideRightTick: true,
  ynames: ['单位：元', '单位：元/m²'],
  names: ['单耗', '费用']
});

useLine({
  id: 'chart_r_1',
  data: data,
  key: 'right1',

});

useBar2({
  id: 'chart_r_2',
  data: data,
  key: 'right2',
  yname: '单位：元/Nm³',
});

useBar2({
  id: 'chart_r_3',
  data: data,
  key: 'right3',
  yname: '单位：元/m³',
});

useLine({
  id: 'chart_r_4',
  data: data,
  key: 'right4',
});

// 组件卸载时清理资源
onUnmounted(() => {
  clearAllTimers();

  // 清理ResizeObserver
  if (resizeObserver.value) {
    resizeObserver.value.disconnect();
    resizeObserver.value = null;
  }
});
</script>
<style lang="less" scoped>
@bg1: rgba(14, 28, 91, 0.60);
@bg2: rgba(36, 108, 249, 0.15);
.premiss-mask{
  background: #0f2957;
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  z-index: 111111;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  color: rgba(255,255,255,0.45);
  .locked{
    width: 160px;
    margin-bottom: 24px;
  }
}
.board-box {
  height: 100%;
  display: grid;
  grid-column-gap: 10px;
  grid-template-columns: 1fr 3fr 1fr;
  grid-template-rows: 1fr;
  overflow: hidden;

  /* 防止内容溢出导致拉伸 */
  .block-header {
    position: relative;
    padding-left: 8px;
    color: #fff;
    font-size: 12px;
    font-weight: 600;
    line-height: 12px;

    &::before {
      content: '';
      position: absolute;
      top: 1px;
      left: 0;
      width: 3px;
      height: 10px;
      border-radius: 3px;
      background: #0067cc;
    }
  }

  .__header-1 {
    box-sizing: border-box;
    height: 32px;
    padding-left: 12px;
    background-image: var(--screenheaderbg1);
    background-size: 100% 100%;
    color: #fff;
    font-size: 14px;
    line-height: 32px;
  }

  .__header-2 {
    box-sizing: border-box;
    height: 36px;
    background-image: var(--screenheaderbg2);
    background-size: 100% 100%;
    color: #fff;
    color: rgba(#fff, .9);
    font-size: 14px;
    font-weight: 600;
    line-height: 36px;
    text-align: center;
  }

  .__header-3 {
    box-sizing: border-box;
    height: 36px;
    background-image: var(--screenheaderbg3);
    background-size: 100% 100%;
    color: #fff;
    font-size: 14px;
    font-weight: 600;
    line-height: 36px;
    text-align: center;
  }

  .chart-box {
    position: relative;

    .chart-title {
      position: absolute;
      z-index: 2;
      top: 0;
      left: 0;
      color: #fff;
    }

    .chart-chart {
      position: absolute;
      z-index: 1;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
  }

  .bottom-chart {
    height: calc(100% - 32px)
  }

  .__left {

    .__left-top {
      display: grid;
      grid-row-gap: 8px;
      grid-template-columns: 1fr;
      grid-template-rows: 32px 1fr 1fr 1fr 1fr 1fr;
      flex-shrink: 0;
      height: 79%;
      padding: 6px;
      background-color: @bg1;
    }

    .__left-bottom {
      flex-shrink: 0;
      height: calc(21% - 10px);
      margin-top: 10px;
      padding: 6px;
      background-color: @bg1;
    }
  }

  .__middle {
    display: flex;
    flex-direction: column;

    .__middle-top {
      display: flex;
      flex-direction: column;
      flex-shrink: 0;
      height: 130px;
      padding: 8px;
      padding-top: 3px;
      padding-bottom: 0;
      background-color: @bg1;
    }

    .__middle-top-box {
      display: flex;
      flex: 1;
      padding: 12px;
      position: relative;
      .__middle-top-item {
        position: relative;
        .__item-line {
          position: absolute;
          right: 0;
          bottom: 0;
          width: 2px;
          height: 50px;
          background: #AC41FF;
        }

        .__item-bar {
          position: absolute;
          right: 0;
          bottom: 0;
          left: 0;
          height: 31px;
          background-image: linear-gradient(270deg, #AB40FF 0%, #8000E3 100%);
        }
      }
      .__item-text {
        position: absolute;
        left: 12px;
        right: 12px;
        bottom: 53px;
        font-size: 16px;
        .__item-text-item{
          color: #AC41FF;
          display: inline-block;
          position: absolute;
          bottom: 0;
        }
        .__item-text-item:first-child{
            color: #00C7C2;
        }
        .__item-text-item:last-child{
            color: #2A72FF;
        }
      }
      .__middle-top-item:first-child {
        

        .__item-line {
          background-color: #00C7C2;
        }

        .__item-bar {
          background-image: linear-gradient(270deg, #00E5E3 0%, #00C7C2 100%);
        }
      }

      .__middle-top-item:nth-child(3) {
        

        .__item-line {
          background-color: #2A72FF;
        }

        .__item-bar {
          background-image: linear-gradient(270deg, #2493FF 0%, #2A72FF 100%);
        }
      }
    }

    .__middle-bottom {
      flex: 1;
      margin-top: 3px;
      padding: 10px;
      border: 1px solid rgb(36 108 249 / 35%);
      background-color: @bg2;

      .__middle-bottom-box {
        display: flex;
        height: calc(100% - 44px);
        margin-top: 8px;
        gap: 10px;

        .__middle-top-item {
          position: relative;
        }
      }

      .__middle-bottom-item {
        display: grid;
        grid-row-gap: 8px;
        grid-template-columns: 1fr;
        grid-template-rows: 32px 1fr;
        flex: 1;

      }

      .__item-chart-box {
        display: grid;
        grid-row-gap: 8px;
        grid-template-columns: 1fr;
        grid-template-rows: 1fr 1fr 1fr;
        padding: 8px;
        border: 1px solid rgb(60 117 255 / 20%);
        background: rgb(14 28 91 / 60%);
      }
    }
  }

  .__right {
    display: flex;
    flex-direction: column;

    .top {
      display: flex;
      flex-direction: column;
      height: 23%;
      margin-bottom: 10px;
      padding: 6px 6px 0;
      color: #fff;

      .ant-tabs {
        padding: 0 6px;
        background-color: @bg1;
        color: #fff;

        :deep(.ant-tabs-nav) {
          margin: 0;
        }

        :deep(.ant-tabs-tab) {
          padding: 6px 0;
          font-size: 12px;
        }
      }

      .data-box {
        flex: 1;
        background: rgb(14 28 91 / 60%);
      }
    }

    .__right-top {
      display: grid;
      grid-row-gap: 8px;
      grid-template-columns: 1fr;
      grid-template-rows: 32px 1fr 1fr 1fr;
      flex: 1;
      flex-shrink: 0;
      padding: 6px;
      background-color: @bg1;
    }

    .__right-bottom {
      flex-shrink: 0;
      height: 25%;
      margin-top: 10px;
      padding: 6px;
      background-color: @bg1;
    }
  }
}
</style>